
#include "InputEngine.h"
#include "Weapon.h"


InputEngine * InputEngine::INSTANCE = NULL;
InputEngine * InputEngine::getInstance()
{
	if (InputEngine::INSTANCE == NULL) {
		InputEngine::INSTANCE = new InputEngine();
	}
	
	return InputEngine::INSTANCE;
}

InputEngine::InputEngine(World * world)
{
	this->world = world;
	this->leftMousePressed = false;
}


void
InputEngine::processInputs ()
{
	if (this->leftMousePressed) {
		Player *p = world->getPlayer();
		if (p->canShoot()) {
			Weapon *w = p->shoot(world->getTimeElapsed());
			world->addFastObject(w);
		}
	}
	
	processPressedKeys();
	this->leftMousePressed = false;
}

void 
InputEngine::processPressedKeys()
{
	Player * player = world->getPlayer();
	std::set< int >::iterator k;
	
	
	for (k = keys.begin(); k != keys.end(); ++k) {
		switch (*k) {
			case  Qt::Key_Right:
				player->moveRight();
				break;
			case Qt::Key_Left:
				player->moveLeft();
				break;
			case Qt::Key_Up:
				player->moveUp();
				break;
			case Qt::Key_Down:
				player->moveDown();
				break;
			case Qt::Key_W:
				player->accelerate();
				break;
			case Qt::Key_S:
				player->brake();
				break;
			case Qt::Key_A:
				player->rollCounterClockwise();
				break;
			case Qt::Key_D:
				player->rollClockwise();
				break;
			case Qt::Key_Escape:
				exit(0);
				break;
			case Qt::Key_Space :
				if (world->getPlayer()->canShoot())
					world->addFastObject(world->getPlayer()->shoot(world->getTimeElapsed()));
				break;
			default :
				break;
				
		}
	}
	
}

bool
InputEngine::mousePressed (QMouseEvent *e)
{
	if (e->button() == Qt::LeftButton)
		this->leftMousePressed = true;
	return true;
}

bool 
InputEngine::keyPressEvent( QKeyEvent * e )
{
	switch (e->key()) {
		case Qt::Key_H:
			world->getPlayer()->getWeapon()->modifyStrength(5.0);
			break;
		case Qt::Key_J:
			world->getPlayer()->getWeapon()->modifyRechargeTime(-8.0);
			break;
	}
	keys.insert(e->key());	
	return  false;
}

bool InputEngine::keyReleaseEvent( QKeyEvent *e )
{
	keys.erase(e->key());
	return false;
}